<template>
  <a-select
    v-model="selectedId"
    :loading="loading"
    :allow-search="allowSearch"
    :allow-clear="allowClear"
    :disabled="disable"
    :options="list"
    :placeholder="placeholder"
    :multiple="multiple"
    :field-names="{
      value: 'id',
      label: 'description',
    }"
    @change="handleChangeSelector"
  ></a-select>
</template>

<script lang="ts" setup>
  import { ref, defineProps, defineEmits, watch } from 'vue';
  import useLoading from '@/hooks/loading';
  import { HostVO, getHostList } from '@/api/host-management';

  const { loading, setLoading } = useLoading();
  const props = defineProps({
    placeholder: {
      type: String,
      default: () => {
        return '请选择接口主机';
      },
    },
    groupId: {
      type: String,
      default: () => {
        return '';
      },
    },
    multiple: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
    allowSearch: {
      type: Boolean,
      default: () => {
        return true;
      },
    },
    allowClear: {
      type: Boolean,
      default: () => {
        return true;
      },
    },
    disable: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
  });
  const emit = defineEmits(['update:modelValue', 'change']);
  const list = ref<HostVO[]>([]);
  const selectedId = ref();

  const handleChangeSelector = () => {
    emit(
      'change',
      props.multiple
        ? list.value.filter((item: any) => selectedId.value.includes(item.id))
        : list.value.find((item: any) => item.id === selectedId.value)
    );
  };

  const fetchData = async () => {
    setLoading(true);
    try {
      const { data } = await getHostList({
        groupId: props.groupId,
        page: 1,
        rows: 999,
      });
      list.value = data.rows;
    } finally {
      setLoading(false);
    }
  };
  watch(
    () => props.groupId,
    (n, o) => {
      if (n !== o) {
        fetchData();
      }
    }
  );
  fetchData();
</script>
